package hcb.dms.khuVuc;

import hcb.dms.JSONParser;
import hcb.dms.R;
import hcb.dms.UserSessionManager;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Edit_khuVuc extends ActionBarActivity {

	EditText txMaKV,txTenKV,txMaNV,txGiaoHang;
	Button btnSave, btnDelete;

	String pid;
	JSONObject objX;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();
	JSONObject product;

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_MESSAGE = "message";
	private static final String TAG_KHUVUC = "khuVuc";
	private static final String TAG_MAKV = "maKV";
	private static final String TAG_TENKV = "tenKV";
	private static final String TAG_GPSLAT = "gpsLat";
	private static final String TAG_GPSLONG = "gpsLong";
	private static final String TAG_LISTGPS = "listGPS";
	private static final String TAG_MANV = "maNV";
	private static final String TAG_NHOM = "nhom";
	private static final String TAG_NGAYBEGIN = "ngayBegin";
	private static final String TAG_NGAYEND = "ngayEnd";
	private static final String TAG_MADATA = "maData";
	private static final String TAG_GIAOHANG = "giaoHang";
	private static final String TAG_CREATELOG = "createLog";
	private static final String TAG_LASTMODIFYLOG = "lastModifyLog";


	UserSessionManager session;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_khu_vuc);
		session = new UserSessionManager(getApplicationContext());
		// save button
		btnSave = (Button) findViewById(R.id.btSave);
		btnDelete = (Button) findViewById(R.id.btDelete);

		// getting product details from intent
		Intent i = getIntent();

		// getting product id (pid) from intent
		pid = i.getStringExtra(TAG_MAKV);
		// Getting complete product details in background thread
		new GetKhuVucDetails().execute();

		// save button click event
		btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// starting background task to update product
				new SaveKhuVucDetails().execute();
			}
		});

		// Delete button click event
		btnDelete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// deleting product in background thread
				new DeleteKhuVuc().execute();
			}
		});
	}
	class GetKhuVucDetails extends AsyncTask<String, String, JSONObject> {

		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khuVuc.this);
			pDialog.setMessage("Loading khu vực. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Getting product details in background thread
		 */
		protected JSONObject doInBackground(String... params) {
			int success;
			try {
				//Building Parameters
				// Building Parameters
				List<NameValuePair> paramas = new ArrayList<NameValuePair>();
				paramas.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
				paramas.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
				paramas.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
				paramas.add(new BasicNameValuePair(session.TAG_THAOTAC, "LKVBID"));
				paramas.add(new BasicNameValuePair(session.TAG_PID,pid));
				//getting product details by making HTTP request
				//Note that product details url will use GET request
				JSONObject json = jsonParser.makeHttpRequest(session.URL, "POST", paramas);

				success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					//successfully received product details
					JSONArray productObj = json.getJSONArray(TAG_KHUVUC); //JSON Array

					//get first product object from JSON Array
					product = productObj.getJSONObject(0);
					return product;

				} else {
					//product with pid not found
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
	/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		//After completing background task dismiss the progress dialog
		protected void onPostExecute(JSONObject obj) {
			//Edit text
			txMaKV = (EditText) findViewById(R.id.txMaKV);
			txTenKV = (EditText) findViewById(R.id.txTenKV);
			txMaNV = (EditText) findViewById(R.id.txMaNV);
			txGiaoHang = (EditText) findViewById(R.id.txGiaoHang);

			objX = obj;
			//display product data in editText
			try {
				txMaKV.setText(obj.getString(TAG_MAKV));
				txTenKV.setText(obj.getString(TAG_TENKV));
				txMaNV.setText(obj.getString(TAG_MANV));
				txGiaoHang.setText(obj.getString(TAG_GIAOHANG));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			//dismiss the dialog once got all details
			pDialog.dismiss();
		}
	}

	/**
	 * Background Async Task to  Save product Details
	 */
	class SaveKhuVucDetails extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khuVuc.this);
			pDialog.setMessage("Saving Khu vực ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Saving product
		 */
		protected String doInBackground(String... args) {

			// getting updated data from EditTexts
			txMaKV = (EditText) findViewById(R.id.txMaKV);
			txTenKV = (EditText) findViewById(R.id.txTenKV);
			txMaNV = (EditText) findViewById(R.id.txMaNV);
			txGiaoHang = (EditText) findViewById(R.id.txGiaoHang);
			String maKV = txMaKV.getText().toString();
			String tenKV = txTenKV.getText().toString();
			String maNV = txMaNV.getText().toString();
			String giaoHang = txGiaoHang.getText().toString();

			try {
				objX.put(TAG_MAKV, maKV);
				objX.put(TAG_TENKV,tenKV);
				objX.put(TAG_MANV,maNV);
				objX.put(TAG_GIAOHANG,giaoHang);
			} catch (JSONException e) {
				e.printStackTrace();
			}


			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "UKV"));
			params.add(new BasicNameValuePair(session.TAG_PID,pid));
			params.add(new BasicNameValuePair(session.TAG_OBJ, objX.toString()));


			// sending modified data through http request
			// Notice that update product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(session.URL,"POST", params);

			// check json success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHUVUC);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(),mess.toString(),Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out",json.toString());
			}

			return null;
		}


		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			// dismiss the dialog once product uupdated
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thông báo: " + str.toString(), Toast.LENGTH_LONG);
			}
			finish();
			pDialog.dismiss();
		}
	}

	/**
	 * **************************************************************
	 * Background Async Task to Delete Product
	 */
	class DeleteKhuVuc extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_khuVuc.this);
			pDialog.setMessage("Deleting Khu vực...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Deleting product
		 */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "DKV"));
			params.add(new BasicNameValuePair(session.TAG_PID, pid));
			params.add(new BasicNameValuePair(session.TAG_OBJ, objX.toString()));
			JSONObject json = jsonParser.makeHttpRequest(session.URL, "POST", params);
			// check your log for json response
			// json success tag

			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHUVUC);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(), mess.toString(), Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out", json.toString());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thông báo: " + str.toString(), Toast.LENGTH_LONG);
			}
			else
			finish();
			pDialog.dismiss();

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_khu_vuc, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
